import React, {Component} from 'react'
import {List, Button, NavBar, Icon} from 'antd-mobile'
import CInput from '../../components/c_input'
import { createForm } from 'rc-form'
import {modal, post} from '../../common/js/utils'
import DefaultLayout from '../../layouts/default_layout'
import {withRouter} from 'react-router-dom'

@createForm()
@withRouter
class Password extends Component {

  onSubmit = (e) => {
    if (e.keyCode === 13) {
      this.doUpdate()
    }
  }

  doUpdate = () => {
    const {history} = this.props
    this.props.form.validateFields((errors, values) => {
      if (!errors) {
        post('/users/password', values, loading => { modal.loading(loading) }).then(res => {
          if (res.result === 1) {
            history.replace('/')
            window.location.reload()
          }
        }).catch(() => {})
      }
    })
  }

  render() {
    const { getFieldValue } = this.props.form
    const { history } = this.props
    return (
      <DefaultLayout
        header={
          <NavBar
            mode="light"
            icon={<Icon type="left" />}
            onLeftClick={() => {
              history.go(-1)
            }}
          >修改密码</NavBar>
        }
      >
        <List renderHeader={'修改密码'}>
          <CInput
            form={this.props.form}
            rules={[{
              required: true,
              message: '请输入原密码'
            }]}
            type={'text'}
            placeholder={'请输入原密码'}
            name={'oldpassword'}
            clear
          >原密码：</CInput>
          <CInput
            form={this.props.form}
            rules={[{
              required: true,
              message: '请输入新密码'
            }]}
            type={'password'}
            placeholder={'请输入新密码'}
            name={'password'}
            clear
          >新密码：</CInput>
          <CInput
            form={this.props.form}
            rules={[{
              required: true,
              message: '请再次填写密码'
            }, {
              validator: (rule, value, callback, source, options) => {
                const password = getFieldValue('password')
                if (password === value) {
                  callback()
                } else {
                  callback(new Error('两次密码输入不一致'))
                }
              }
            }]}
            type={'password'}
            placeholder={'请再次填写密码'}
            name={'repassword'}
            onKeyDown={this.onSubmit}
            clear
          >重复密码：</CInput>
          <div
            style={{
              padding: 5
            }}
          >
            <Button
              onClick={this.doUpdate}
              type={'primary'}
              size={'large'}
            >确认修改</Button>
          </div>
        </List>
      </DefaultLayout>
    )
  }
}

export default Password
